package com.example.mqttledmenu;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.transition.DrawableCrossFadeFactory;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;

import retrofit2.Call;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import java.util.UUID;

public class FragmentLaunch extends Fragment {

    private static final String ARG_PARAM1 = "param1";
    private static final int REQUEST_GALLERY = 100;
    private String mParam1;
    private View rootView;
    private Button file_add;
    private Button launch_submit;
    private ImageView file_add_delete;
    private EditText notice_title;
    private EditText notice_content;
    private ImageView upload_image;
    private TextView file_add_name;
    private String uploadFileUrl = "null";
    private SharedPreferences sp;

    //初始化MQTT协议相关变量
    private static MqttAndroidClient mqttAndroidClient;
    String serverUrl = "tcp://test.ranye-iot.net:1883";//使用开源的服务器
    String clientId = "2f339b3eccd94c9da6726fa9a9eee9f3";//客户端的ID
    Boolean isConnect = false;


    public FragmentLaunch() {
        // Required empty public constructor
    }

    public static FragmentLaunch newInstance(String param1, String param2) {
        FragmentLaunch fragment = new FragmentLaunch();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        fragment.setArguments(args);
        return fragment;
    }

    public void initNewsCache() {
        //检测密码信息
        sp = getActivity().getSharedPreferences("news_cache", Context.MODE_PRIVATE);
        Boolean has_cache = sp.getBoolean("has_cache", false);
        if (has_cache) {
            notice_title.setText(sp.getString("title", ""));
            notice_content.setText(sp.getString("content", ""));
            String remote_url = sp.getString("img_remote", "").replace("\"", "");
            uploadFileUrl = remote_url;
            Glide.with(this)
                    .load(remote_url)
                    .into(upload_image);
            file_add_name.setText(remote_url.substring(remote_url.lastIndexOf("/") + 1));
        } else {

        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
        }
        initMQTTService();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_launch, container, false);
        }
        initView();
        initNewsCache();

        return rootView;
    }


    public void initMQTTService() {
        clientId = clientId + System.currentTimeMillis(); // 获取系统运行时间,保证ID的唯一性
        mqttAndroidClient = new MqttAndroidClient(getContext(), serverUrl, clientId);
        mqttAndroidClient.setCallback(new MqttCallbackExtended() {
            public void connectComplete(boolean reconnect, String serverUrl) {
                if (!isConnect && reconnect) {
                    isConnect = true;
                }
            }

            @Override
            public void connectionLost(Throwable cause) {
                Toast.makeText(getContext(), "MQTT服务重连失败！", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
                //noticeInfo(message.toString());
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {
                Toast.makeText(getContext(), "  消息发送完成！", Toast.LENGTH_SHORT).show();
            }
        });
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();//定义一个mqttConnectOptions
        mqttConnectOptions.setAutomaticReconnect(true);//自动重连
        mqttConnectOptions.setCleanSession(false);//不清除会话
        try {
            mqttAndroidClient.connect(mqttConnectOptions, null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    // Toast.makeText(getContext(), "MQTT服务器连接成功！", Toast.LENGTH_SHORT).show();
                    isConnect = true;
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    Toast.makeText(getContext(), "MQTT服务器首次连接失败~", Toast.LENGTH_SHORT).show();
                }
            });
        } catch (MqttException ex) {
            ex.printStackTrace();
        }
    }


    //发布主题
    public void publishToTopic(String publishTopic, String message) {
        try {
            //参数分别为：主题、消息的字节数组、服务质量、是否在服务器保留断开连接后的最后一条消息
            mqttAndroidClient.publish(publishTopic, message.getBytes(), 0, true);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    public void initView() {
        //绑定文本编辑按钮
        notice_title = rootView.findViewById(R.id.notice_title);
        notice_content = rootView.findViewById(R.id.notice_content);
        //上传的图片
        upload_image = rootView.findViewById(R.id.upload_image);
        //上传的文件名
        file_add_name = rootView.findViewById(R.id.file_add_name);
        //上传附件按钮
        file_add = rootView.findViewById(R.id.file_add);
        //删除上传附件按钮
        file_add_delete = rootView.findViewById(R.id.file_add_delete);
        //发布按钮
        launch_submit = rootView.findViewById(R.id.launch_submit);
        launch_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String title = notice_title.getText().toString();
                String content = notice_content.getText().toString();
                if (title.equals("") || content.equals("")) {
                    Toast.makeText(getActivity(), "通知标题和通知内容不得为空！", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    //发布内容
                    Retrofit retrofit = new Retrofit.Builder().baseUrl(Config.serverUrl).build();
                    UploadService uploadService = retrofit.create(UploadService.class);
                    Call<ResponseBody> call = uploadService.publish(Config.getInstance().getUserId(), title, content, uploadFileUrl);//与后端约定，不传入id直接获取全部
                    call.enqueue(new Callback<ResponseBody>() {
                        @Override
                        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                            String result = null;
                            try {
                                result = response.body().string();
                                JsonObject returnData = new JsonParser().parse(result).getAsJsonObject();
                                if (!returnData.get("code").toString().equals("200")) {
                                    Toast.makeText(getActivity(), "服务端错误~", Toast.LENGTH_SHORT).show();
                                    return;
                                } else {
                                    JsonObject jsonObject = (JsonObject) returnData.get("data");
                                    String publicId = jsonObject.get("publicId").toString();
                                    String temp = new PublishNews(title, Config.getInstance().getDepartmentName(), publicId).ChangeToString();
                                    publishToTopic(Config.getInstance().getDepartmentTag(), temp);
                                    Toast.makeText(getActivity(), "发布成功！", Toast.LENGTH_SHORT).show();
                                    SharedPreferences.Editor edit = sp.edit();
                                    edit.putBoolean("has_cache", false);
                                    edit.apply();
                                    notice_title.setText("");
                                    notice_content.setText("");
                                    file_add_name.setText("未上传");
                                    upload_image.setImageResource(R.drawable.upload_default_img);
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onFailure(Call<ResponseBody> call, Throwable t) {

                        }
                    });
                }
            }
        });


        file_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                OpenFile(view);
            }
        });

        file_add_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                file_add_name.setText("未上传");
                upload_image.setImageResource(R.drawable.upload_default_img);
                Toast.makeText(getActivity(), "已删除上传的附件~", Toast.LENGTH_SHORT).show();
                uploadFileUrl = "null";
            }
        });
    }


    private void OpenFile(View view) {
        Intent galleryIntent = new Intent(Intent.ACTION_PICK); // 系统默认的图片选择程序
        galleryIntent.setType("image/*");
        startActivityForResult(galleryIntent, REQUEST_GALLERY);
    }

    private void saveUriToFile(Uri uri, int from) {
        Bitmap bitmap = null;
        if (uri != null) {
            try {
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 2; // 图片宽高都为原来的二分之一，即图片为原来的四分之一
                bitmap = BitmapFactory.decodeStream(getContext().getContentResolver().openInputStream(uri), null, options);
                upload_image.setImageBitmap(bitmap);
                //处理文件上传
                String filePath = FileUtils.getRealFilePath(getContext(), uri);
                file_add_name.setText(filePath.substring(filePath.lastIndexOf("/") + 1));
                sendRequest(filePath);
            } catch (Exception e) {
                Toast.makeText(getActivity(), "上传文件失败~", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Uri uri = data.getData();
        saveUriToFile(uri, REQUEST_GALLERY);
    }

    private void sendRequest(String filePath) {
        File file = new File(filePath);
        String newFileName = UUID.randomUUID().toString().replace("-", "") + ".jpg";
        Retrofit retrofit = new Retrofit.Builder().baseUrl(Config.serverUrl).build();
        UploadService uploadService = retrofit.create(UploadService.class);
        MediaType mediaType = MediaType.parse("multipart/form-data");
        RequestBody fileBody = RequestBody.create(mediaType, file);
        MultipartBody.Part part = MultipartBody.Part.createFormData("file", newFileName, fileBody);
        Call<ResponseBody> call = uploadService.upload(part);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.body() != null) {
                    try {
                        String result = response.body().string();
                        Log.d("nightowl", "onResponse(file): " + result);
                        JsonObject returnData = new JsonParser().parse(result).getAsJsonObject();
                        if (!returnData.get("code").toString().equals("200")) {
                            Toast.makeText(getContext(), "服务端错误~", Toast.LENGTH_SHORT).show();
                        } else {
                            uploadFileUrl = returnData.get("data").toString();//记录上传返回之后的图片路径
                            Toast.makeText(getContext(), "文件上传成功！！", Toast.LENGTH_SHORT).show();
                            SharedPreferences.Editor edit = sp.edit();
                            edit.putBoolean("has_cache", true);
                            String title = notice_title.getText().toString();
                            String content = notice_content.getText().toString();
                            edit.putString("title", title);
                            edit.putString("content", content);
                            edit.putString("img_remote", uploadFileUrl);
                            edit.apply();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    Log.d("nightowl", "onResponse -- > " + "返回数据为空");
                }

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.d("nightowl", "onFailure -- > " + t.toString());
            }
        });
    }
}